import { globalApi } from '@/api/global';
import { isURL } from '@/utils/validate';
import { ElMessage } from 'element-plus';
import routes, { moduleRoutes, pageRoutes } from './routes';
import { createRouter, createWebHashHistory } from 'vue-router';

// #region 类型
type RouterValue = {
  path: string;
  component: unknown;
  name: string;
  meta: {
    menuId: string;
    title: string;
    iframeURL: string;
  };
};
// #endregion

// #region 属性
const coreModules = import.meta.glob('../core/**');
const viewModules = import.meta.glob('../views/**');
const modules = Object.assign(coreModules, viewModules);
const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes,
  scrollBehavior(to, from, savedPosition) {
    // return 期望滚动到哪个的位置
    return { top: 0 };
  },
}) as any;
// #endregion

// #region 方法
// 路由守卫、添加路由
router.beforeEach(async (to: any, from: any, next: (arg0?: { name: string }) => void) => {
  // 已添加或者当前路由为页面路由, 可直接访问
  if (window.SITE_CONFIG.isDynamicRoutes || isPageRoute(to, pageRoutes)) {
    return next();
  }
  try {
    // 获取菜单列表, 添加并全局变量保存
    const navRes = await globalApi.getMens();
    if (navRes.code !== 0) {
      ElMessage.error(navRes.msg);
      next({ name: 'login' });
    } else {
      window.SITE_CONFIG.menuList = navRes.data;
      getDynamicRoutes(window.SITE_CONFIG.menuList);
      next({ ...to, replace: true });
    }
  } catch (err) {
    next({ name: 'login' });
  }
});

/**
 * 判断当前路由是否为页面路由
 * @param {*} route 当前路由
 * @param {*} pageRouteArr 页面路由
 */
const isPageRoute = (route: RouterValue, pageRouteArr = [] as any): boolean => {
  let temp: any[] = [];
  for (let i = 0; i < pageRouteArr.length; i++) {
    const item = pageRouteArr[i];
    if (route.path === item.path) {
      return true;
    }
    if (item.children && item.children.length >= 1) {
      temp = temp.concat(item.children);
    }
  }
  return temp.length >= 1 ? isPageRoute(route, temp) : false;
};

/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routeArr 递归创建的动态(菜单)路由
 */
const getDynamicRoutes = (menuList = [] as any, routeArr = [] as any) => {
  let temp: any[] = [];
  for (let i = 0; i < menuList.length; i++) {
    const item = menuList[i];
    if (item.children && item.children.length >= 1) {
      temp = temp.concat(item.children);
      continue;
    }
    // 组装路由
    const routeObj: RouterValue = {
      path: '',
      component: '',
      name: '',
      meta: {
        ...window.SITE_CONFIG.defaultTab,
        menuId: item.id,
        title: item.name,
      },
    } as any;
    // eslint-disable-next-line
    let URL = item.url.replace(/{{([^}}]+)?}}/g, (s1, s2) => eval(s2)); // URL支持{{ window.xxx }}占位符变量
    if (isURL(URL)) {
      routeObj.path = routeObj.name = `i-${item.id}`;
      routeObj.meta.iframeURL = URL;
      routeObj.component = modules['../core/web-view.vue'];
    } else {
      URL = URL.replace(/^\//, '').replace(/_/g, '-');
      routeObj.path = URL.replace(/\//g, '-');
      routeObj.name = URL.replace(/\//g, '-');
      let modulesUrl = `../core/${URL.indexOf('.html') > -1 ? URL : `${URL}.vue`}`;
      if (!modules[modulesUrl]) {
        modulesUrl = `../views/${URL.indexOf('.html') > -1 ? URL : `${URL}.vue`}`;
      }
      routeObj.component = modules[modulesUrl];
    }
    routeArr.push(routeObj);
  }
  if (temp.length >= 1) {
    getDynamicRoutes(temp, routeArr);
    return;
  }
  // 添加路由
  router.addRoute({
    ...moduleRoutes,
    name: 'dynamic-menu',
    children: routeArr,
  });
  router.addRoute({
    path: '/:path(.*)*',
    redirect: { name: '404' },
  });
  window.SITE_CONFIG.dynamicMenuRoutes = routeArr;
  window.SITE_CONFIG.isDynamicRoutes = true;
};
// #endregion
export default router;
